<?php
namespace app\modules\supplier\logic;
use app\modules\base\LogicBase;
use think\Db;
use app\modules\common\TimeCalendar;
use think\Cache;
/**
 *
 */

class FinReportLogic extends LogicBase
{
    protected $TimeCalendar;//时间类
    //筛选
    public $supplier_id = 0;//供应商ID
    public $times_interval = [];//时间间隔 [start,end] date格式
    public $reports_date = '';//初始化报表标题
    public $days = 0; //天数
    public $day_format =[]; //格式化日期范围

    /**
     * 构造函数初始化
     * @param array $init 初始化参数
     * @param [user_department_id] 部门ID
     * @param [$start] 开始时间
     * @param [$end] 结束时间
     * @return bool|array
     */
    public function __construct($init = [])
    {
        $this->TimeCalendar = new TimeCalendar();
        $this->supplier_id = get_supplier_id();
        $this->_initTime($init);


    }


    public function index(){
        if (!empty($this->_error)){
            return false;
        }
         $data = $this->_order();
         return $data;
    }

    public function  goodsSale(){
        if (!empty($this->_error)){
            return false;
        }
        $data = $this->_goodsSale();
        return $data;
    }

    public function supplierPrice(){
        if (!empty($this->_error)){
            return false;
        }
        $data = $this->_supplierPrice();
        return $data;
    }

    public function _goodsSale(){

        $field = "OG.goods_name,COALESCE(SUM(OG.num),0) as num";

        $data =  Db::name('supplier_order')->alias('SO')
            ->field($field)
            ->join('order_goods OG','SO.order_id = OG.order_id','LEFT')
            ->where(['SO.supplier_id'=>$this->supplier_id,'SO.order_status'=>100,'date' => ['BETWEEN', [$this->times_interval['start'], $this->times_interval['end']]]])
            ->group('OG.goods_id')
            ->order('OG.num DESC')
//            ->cache(true,'','ssss')
            ->select();

        return $data;
    }

    public function _supplierPrice(){
        $field = "IFNULL(date,0) as date,
        price_type,
		COALESCE(SUM(price),0) as price
		";

        $_data = Db::name('supplier_price_detail')->field($field)->where(['supplier_id' =>$this->supplier_id,'date' => ['BETWEEN', [$this->times_interval['start'], $this->times_interval['end']]]])->order('date ASC')->group('date,price_type')->select();
        $data =[];
        foreach ($_data as  $key => $val){
            $data[$val['date']]  = $val;
        }
        $report =[];
        foreach ($this->day_format as $key => $val){
            $report[$key]['price'] = isset($data[$key])?$data[$key]['price']:0;
            $report[$key]['price_type'] = isset($data[$key])?$data[$key]['price_type']:'-';
        }

        return $report;
    }

    /**
     * 订单数据 （按date分组）
     * IN store_id
     * @return bool|array
     */
    protected function _order()
    {
        $field = "IFNULL(date,0) as date,
        count(*) as num,
		COALESCE(SUM(order_money),0) as order_money
		";

        $_data = Db::name('supplier_order')->field($field)->where(['supplier_id' =>$this->supplier_id,'date' => ['BETWEEN', [$this->times_interval['start'], $this->times_interval['end']]]])->order('date ASC')->group('date')->select();
        $data =[];
        foreach ($_data as  $key => $val){
            $data[$val['date']]  = $val;
        }

        $report =[];
        foreach ($this->day_format as $key => $val){
           $report[$key]['order_money'] = isset($data[$key])?$data[$key]['order_money']:0;
           $report[$key]['num'] = isset($data[$key])?$data[$key]['num']:0;
        }

        foreach ($report as $key => $val){
            $report['total']['order_money'] += $val['order_money'];
            $report['total']['num'] += $val['num'];
        }

        return $report;

    }

    /**
     * 初始化时间间隔
     * @param array $init 初始化参数
     * @param [user_department_id] 部门ID
     * @param [$start] 开始时间
     * @param [$end] 结束时间
     * @return bool|array
     */
    public function _initTime($init = [])
    {

        $option = [
            'step_section' => 'day',
            'step_by' => 0,
            'day' => 0,
            'week' => 0,
            'month' => 0,
            'quarter' => 0,
            'year' => 0,
            'time_s' => 0,
            'time_e' => 0
        ];

        if (isset($init['step_section'])) {
            $option['step_section'] = trim($init['step_section']);
        }
        if (!in_array($init['step_section'], ['search', 'day', 'week', 'month', 'quarter', 'year'])) {
            $option['step_section'] = 'day';
        }
        if (isset($init['step_by'])) {
            $option['step_by'] = intval($init['step_by']);
        }
        if (isset($init['day'])) {
            $option['day'] = intval($init['day']);
        }
        if (isset($init['week'])) {
            $option['week'] = intval($init['week']);
        }
        if (isset($init['month'])) {
            $option['month'] = intval($init['month']);
        }
        if (isset($init['quarter'])) {
            $option['quarter'] = intval($init['quarter']);
        }
        if (isset($init['year'])) {
            $option['year'] = intval($init['year']);
        }

        if ($option['step_section'] == 'search') {

            if (isset($init['time_s'])) {
                $option['time_s'] = is_numeric($init['time_s']) ? intval($init['time_s']) : strtotime($init['time_s']);
                if (!$option['time_s']) {
                    $this->_error[] = "开始时间无效";
                    return false;
                }
            }else{
                $this->_error[] ='请选择开始时间';
                return false;
            }
            if (isset($init['time_e'])) {
                $option['time_e'] = is_numeric($init['time_e']) ? intval($init['time_e']) : strtotime($init['time_e']);
                if (!$option['time_s']) {
                    $this->_error[] = "开始时间无效";
                    return false;
                }
            }else{
                $this->_error[] ='请选择结束时间';
                return false;
            }
            $reports_date = date('Y年m月d日', $option['time_s']) . "——" . date('Y年m月d日', $option['time_e']);
            $times_interval = [
                'start' => date('Y-m-d', $option['time_s']),
                'end' => date('Y-m-d', $option['time_e'])
            ];

            $days = (int)ceil(($option['time_e'] - $option['time_s']) / (24 * 60 * 60));
        } else {

            switch ($option['step_section']) { //当前日
                case 'day':
                    $times_interval = $this->TimeCalendar->getDayTimesInterval($option['day'] + $option['step_by'], $option['month'], $option['year'], 'Y-m-d');
                    $days = 1;
                    $reports_date = date('Y年m月d日', strtotime($times_interval['start']));
                    break;

                case 'week': //周

                    $times_interval = $this->TimeCalendar->getWeekTimesInterval($option['week'] + $option['step_by'], $option['year'], 'Y-m-d');
                    $days = 7;
                    $reports_date = date('Y年W周', strtotime($times_interval['start'])).' ( '.date('Y年m月d日', strtotime($times_interval['start'])).'—'.date('Y年m月d日', strtotime($times_interval['end'])).' )';
                    break;

                case 'month': //月
                    $times_interval = $this->TimeCalendar->getMonthTimesInterval($option['month'] + $option['step_by'], $option['year'], 'Y-m-d');
                    $days = $this->TimeCalendar->getMonthDays($option['month'] + $option['step_by'], $option['year']);
                    $reports_date = date('Y年m月', strtotime($times_interval['start']));
                    break;
                case 'quarter': //月
                    $times_interval = $this->TimeCalendar->getQuarterTimesInterval($option['quarter'] + $option['step_by'], $option['year'], 'Y-m-d');
                    $days = $this->TimeCalendar->getQuarterDays($option['quarter'] + $option['step_by'], $option['year']);
                    $m = date('m', strtotime($times_interval['start']));
                    if ($m <= 3) {
                        $quarter = 1;
                    } else if ($m <= 6) {
                        $quarter = 2;
                    } else if ($m <= 9) {
                        $quarter = 3;
                    } else {
                        $quarter = 4;
                    }
                    $reports_date = date('Y年' . $quarter . '季度', strtotime($times_interval['start'])).' ( '.date('Y年m月d日', strtotime($times_interval['start'])).'—'.date('Y年m月d日', strtotime($times_interval['end'])).' )';

                    break;
                case 'year': //月
                    $times_interval = $this->TimeCalendar->getYearTimesInterval($option['year'] + $option['step_by'], 'Y-m-d');
                    $days = $this->TimeCalendar->getYearDays($option['year'] + $option['step_by']);
                    $reports_date = date('Y年统计', strtotime($times_interval['start']));
                    break;
                default:
                    //Day
                    $times_interval = $this->TimeCalendar->getDayTimesInterval($option['day'] + $option['step_by'], $option['month'], $option['year'], 'Y-m-d');
                    $days = 1;
                    $reports_date = date('Y年m月d日', strtotime($times_interval['start']));
                    break;
            }
        }
        if ($times_interval['start'] > $times_interval['end']) {
            $this->_error[] = "统计区间时间无效,截止时间必须要大于开始时间";
            return false;
        }

        $date_format = [];
        for ($i = 0; $i < $days; $i++) {
            $date_format[date('Y-m-d', strtotime($times_interval['start']) + $i * (24 * 60 * 60))]['start'] = strtotime($times_interval['start']) + $i * (24 * 60 * 60);
            $date_format[date('Y-m-d', strtotime($times_interval['start']) + $i * (24 * 60 * 60))]['end'] = strtotime($times_interval['start'])  + ($i + 1) * (24 * 60 * 60) - 1;
        }

        $this->reports_date = $reports_date;
        $this->times_interval = $times_interval;
        $this->days = $days;
        $this->day_format = $date_format;
    }
}